﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chowpoo.Sql;
using CourseSystem.Core.Entities;
using CourseSystem.Core.SqlServerDAL;

namespace CourseSystem.Core.BLL
{
    public class ExamAnswerBLL : CommonBLL<ExamAnswerInfo, ExamAnswerDAL>
    {
        /// <summary>
        /// 删除列表中没有,有则更新,无就添加
        /// </summary>
        /// <param name="eid"> </param>
        /// <param name="uid"> </param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool EditList(int eid, int uid, List<ExamAnswerInfo> list)
        {
            var qidList = list.Select(o => o.Qid).ToList();
            if (qidList.Count < 1)
            {
                return false;
            }
            using (var dal = new ExamAnswerDAL())
            {
                dal.Delete(o => o.Eid == eid && o.Uid == uid && !qidList.Contains(o.Qid));
                var existList = dal.Select(o => o.Eid == eid && o.Uid == uid);
                var addList = new List<ExamAnswerInfo>();
                var editList = new List<ExamAnswerInfo>();
                foreach (var item in list)
                {
                    var existInfo = existList.FirstOrDefault(o => o.Qid == item.Qid);
                    if (existInfo == null)
                        addList.Add(item);
                    else
                    {
                        existInfo.Answer = item.Answer;
                        existInfo.AnswerId = item.AnswerId;
                        existInfo.Score = item.Score;
                        editList.Add(existInfo);
                    }
                }
                return (dal.Add(addList) != null) && (dal.Update(editList) != null);
            }
        }

        public static ExamAnswerInfo Get(int id)
        {
            using (var dal = new ExamAnswerDAL())
            {
                var re = dal.SelectSingle(o => o.Id == id);
                return re;
            }
        }

        public static bool Del(int id)
        {
            using (var dal = new ExamAnswerDAL())
            {
                return dal.Delete(o => o.Id == id) != null;
            }
        }

    }
}
